import axios from "axios";
import type {
  AxiosInstance,
  AxiosResponse,
  CreateAxiosDefaults,
  InternalAxiosRequestConfig,
} from "axios";

// 封装 Axios 类
class Tea {
  // 请求实例
  private instance: AxiosInstance;
  constructor(config: CreateAxiosDefaults) {
    this.instance = axios.create(config); // 创建实例
    // 实例化后调用拦截方法
    this.beforeRequest();
    this.beforeResponse();
  }
  // 拦截
  private beforeRequest() {
    // 请求拦截
    this.instance.interceptors.request.use(
      (req: InternalAxiosRequestConfig) => {
        return req;
      }
    );
  }
  private beforeResponse() {
    // 响应拦截
    this.instance.interceptors.response.use((res: AxiosResponse) => {
      return res;
    });
  }

  // GET 请求
  get<T>(url: string, params?: T,headers?:Record<string, string>): Promise<AxiosResponse> {
    return this.instance({
      method: "get",
      params, // 把对象拼装在路径后面
      url,
      headers: headers || {}
    });
  }

  //delete 请求
  delete<T>(url: string, params?: T): Promise<AxiosResponse> {
    return this.instance({
      method: "delete",
      params,
      url,
    });
  }

  // POST 请求
  post<T>(url: string, data?: T): Promise<AxiosResponse> {
    return this.instance({
      method: "post",
      data,
      url,
    });
  }

  // PUT 请求
  put<T>(url: string, data?: T): Promise<AxiosResponse> {
    return this.instance({
      method: "put",
      data,
      url,
    });
  }
}

export default Tea;
